package com.javalong.affairs.listener;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import org.apache.http.HttpEntity;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.javalong.affairs.multirequest.MultipartRequestParams;
import com.javalong.affairs.utils.CookieUtils;

public class MultipartRequest extends Request<JSONObject> {
	private MultipartRequestParams params = null;
	private HttpEntity httpEntity = null;
	private BaseResponseListener listener;

	public MultipartRequest(String url, MultipartRequestParams params,
			BaseResponseListener listener) {
		this(Method.POST, params, url, null, listener);
	}

	public MultipartRequest(int method, MultipartRequestParams params,
			String url, Context context, BaseResponseListener listener) {
		super(method, url, null);
		this.params = params;
		this.listener = listener;
	}

	@Override
	public byte[] getBody() throws AuthFailureError {
		// TODO Auto-generated method stub
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		if (params != null) {
			httpEntity = params.getEntity();
			try {
				if (httpEntity != null) {
					httpEntity.writeTo(baos);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			String str = new String(baos.toByteArray());
		}
		return baos.toByteArray();
	}

	@Override
	protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
		// TODO Auto-generated method stub
		try {
			String jsonString = new String(response.data,
					HttpHeaderParser.parseCharset(response.headers));
			return Response.success(new JSONObject(jsonString),
					HttpHeaderParser.parseCacheHeaders(response));
		} catch (UnsupportedEncodingException e) {
			return Response.error(new ParseError(response));
		} catch (JSONException je) {
			return Response.error(new ParseError(response));
		}
	}

	@Override
	public Map<String, String> getHeaders() throws AuthFailureError {
		Map<String, String> headers = super.getHeaders();
		if (null == headers || headers.equals(Collections.emptyMap())) {
			headers = new HashMap<String, String>();
		}
		headers.put("Cookie", CookieUtils.getSessionHeader());
		return headers;
	}

	@Override
	public String getBodyContentType() {
		if (httpEntity != null && httpEntity.getContentType() != null) {
			return httpEntity.getContentType().getValue();
		}
		return "multipart/form-data";
	}

	@Override
	protected void deliverResponse(JSONObject arg0) {
		if (listener != null) {
			listener.onResponse(arg0.toString());
		}
	}
}